import { PlatformType } from './modules/platformHelper';
import * as os from 'os';
import * as path from 'path';
import * as fs from 'fs';
import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);

// Mock vscode API for testing without vscode
const vscodeMock = {
    window: {
        showInformationMessage: (message: string, ...items: string[]): Promise<string | undefined> => {
            console.log(`[Info] ${message}`);
            return Promise.resolve(undefined);
        },
        showWarningMessage: (message: string, ...items: string[]): Promise<string | undefined> => {
            console.log(`[Warning] ${message}`);
            return Promise.resolve(undefined);
        },
        showErrorMessage: (message: string, ...items: string[]): Promise<string | undefined> => {
            console.log(`[Error] ${message}`);
            return Promise.resolve(undefined);
        }
    },
    Uri: {
        parse: (path: string) => ({ path })
    },
    commands: {
        executeCommand: (command: string, ...args: any[]): Promise<any> => {
            console.log(`[Command] ${command}`);
            return Promise.resolve(undefined);
        }
    },
    EventEmitter: class {
        event: any;
        constructor() {
            this.event = () => {};
        }
        fire(data: any) {
            console.log('[Event fired]', data);
        }
    }
};

// Mock PlatformHelper for testing
class PlatformHelperMock {
    private static instance: PlatformHelperMock;
    private platformType: PlatformType;
    private isWSL: boolean = false;
    private isRootless: boolean = false;
    private isAdmin: boolean = false;

    private constructor() {
        // 初始化时检测平台类型
        const platform = os.platform();
        
        if (platform === 'win32') {
            this.platformType = PlatformType.WINDOWS;
        } else if (platform === 'darwin') {
            this.platformType = PlatformType.MACOS;
        } else if (platform === 'linux') {
            this.platformType = PlatformType.LINUX;
            // 检测 WSL
            try {
                const releaseContent = fs.readFileSync('/proc/version', 'utf8').toLowerCase();
                this.isWSL = releaseContent.includes('microsoft') || releaseContent.includes('wsl');
                if (this.isWSL) {
                    this.platformType = PlatformType.WSL;
                }
            } catch (error) {
                // 不是 WSL
            }
        } else {
            // 默认为 Linux
            this.platformType = PlatformType.LINUX;
        }
    }

    public static getInstance(): PlatformHelperMock {
        if (!PlatformHelperMock.instance) {
            PlatformHelperMock.instance = new PlatformHelperMock();
        }
        return PlatformHelperMock.instance;
    }

    public getPlatformType(): PlatformType {
        return this.platformType;
    }

    public isWindows(): boolean {
        return this.platformType === PlatformType.WINDOWS;
    }

    public isMacOS(): boolean {
        return this.platformType === PlatformType.MACOS;
    }

    public isLinux(): boolean {
        return this.platformType === PlatformType.LINUX;
    }

    public isWSLEnvironment(): boolean {
        return this.isWSL;
    }

    public isRootlessEnvironment(): boolean {
        return this.isRootless;
    }

    public isAdminPrivileged(): boolean {
        return this.isAdmin;
    }

    public async checkUserPrivileges(): Promise<void> {
        try {
            if (this.isWindows()) {
                // Windows 权限检查
                try {
                    await execAsync('net session >nul 2>&1');
                    this.isAdmin = true;
                } catch {
                    this.isAdmin = false;
                }
            } else {
                // macOS/Linux 权限检查
                const { stdout } = await execAsync('id -u');
                this.isAdmin = stdout.trim() === '0';
            }
            
            // 检查容器运行时是否为 rootless 模式
            await this.checkRootlessContainerRuntime();
        } catch (error) {
            console.log('User privileges check error:', error);
            this.isAdmin = false;
        }
    }

    private async checkRootlessContainerRuntime(): Promise<void> {
        try {
            // 检查 Docker 是否运行在 rootless 模式
            try {
                const { stdout: dockerInfo } = await execAsync('docker info 2>/dev/null || echo "Docker not available"');
                this.isRootless = dockerInfo.includes('rootless') || dockerInfo.includes('Rootless');
                
                if (!this.isRootless) {
                    // 如果 Docker 不是 rootless 模式，检查 Podman
                    try {
                        const { stdout: podmanInfo } = await execAsync('podman info 2>/dev/null || echo "Podman not available"');
                        // Podman 默认是 rootless 的，但我们仍然明确检查
                        this.isRootless = podmanInfo.includes('rootless') || !podmanInfo.includes('Podman not available');
                    } catch {
                        // Podman 可能不可用，保持之前的值
                    }
                }
            } catch (error) {
                // Docker 命令失败，忽略
            }
        } catch (error) {
            console.log('Rootless check error:', error);
            this.isRootless = false;
        }
    }

    public isPrivilegedPort(port: number): boolean {
        // Windows 没有特权端口的概念
        if (this.isWindows()) {
            return false;
        }
        
        // 在 Unix 系统上，小于 1024 的端口被认为是特权端口
        return port < 1024;
    }

    public suggestNonPrivilegedPort(desiredPort: number): number {
        if (desiredPort >= 1024) {
            return desiredPort; // 已经是非特权端口
        }
        
        // 为特权端口建议一个替代端口
        const portMap: Record<number, number> = {
            80: 8080,
            443: 8443,
            21: 2121,
            22: 2222,
            25: 2525
        };
        
        return portMap[desiredPort] || 8000 + desiredPort;
    }

    public async convertPathForContainer(originalPath: string): Promise<string> {
        try {
            if (this.isWSL) {
                // 如果是 WSL 环境，需要将路径转换为 Windows 路径
                try {
                    const { stdout } = await execAsync(`wslpath -w "${originalPath}"`);
                    return stdout.trim();
                } catch {
                    return originalPath;
                }
            } else if (this.isWindows()) {
                // Windows 环境下，需要处理路径分隔符
                return originalPath.replace(/\\/g, '/');
            } else {
                // macOS 和 Linux 可以直接使用路径
                return originalPath;
            }
        } catch (error) {
            console.error('Path conversion error:', error);
            return originalPath; // 转换失败时返回原路径
        }
    }

    public async showPortPermissionGuide(port: number): Promise<void> {
        if (!this.isPrivilegedPort(port)) {
            return; // 非特权端口不需要处理
        }
        
        if (this.isMacOS()) {
            console.log(`端口 ${port} 需要管理员权限。在 macOS 上，建议使用非特权端口 ${this.suggestNonPrivilegedPort(port)}`);
        } else if (this.isLinux() || this.isWSLEnvironment()) {
            console.log(`端口 ${port} 需要管理员权限。在 ${this.isWSLEnvironment() ? 'WSL' : 'Linux'} 上，建议使用非特权端口 ${this.suggestNonPrivilegedPort(port)}`);
        }
    }

    public getContainerOptions(containerType: 'docker' | 'podman'): Record<string, string> {
        const options: Record<string, string> = {};
        
        if (this.isWSLEnvironment() && containerType === 'docker') {
            // WSL 环境中的 Docker 需要特殊处理
            options.host = '-H npipe:////./pipe/docker_engine';
        }
        
        if (this.isWindows() && containerType === 'podman') {
            // Windows 环境下的 Podman 可能需要特殊处理
            options.connection = '--connection podman-machine-default';
        }
        
        return options;
    }
}

/**
 * 平台功能测试 - 跨平台支持
 */
async function testPlatformSupport(): Promise<void> {
    console.log('========== 开始测试平台支持功能 ==========\n');

    // 获取平台帮助器实例
    const platformHelper = PlatformHelperMock.getInstance();
    
    // 测试平台检测
    console.log('----- 测试平台检测 -----');
    const platformType = platformHelper.getPlatformType();
    console.log(`检测到的平台类型: ${platformType}`);
    console.log(`操作系统: ${os.platform()} ${os.release()}`);
    
    if (platformHelper.isWindows()) {
        console.log('✅ 当前是 Windows 平台');
    } else if (platformHelper.isMacOS()) {
        console.log('✅ 当前是 macOS 平台');
    } else if (platformHelper.isLinux()) {
        console.log('✅ 当前是 Linux 平台');
    }
    
    if (platformHelper.isWSLEnvironment()) {
        console.log('✅ 当前是 WSL 环境');
    }
    
    // 测试权限检测
    console.log('\n----- 测试权限检测 -----');
    await platformHelper.checkUserPrivileges();
    console.log(`管理员权限: ${platformHelper.isAdminPrivileged() ? '是' : '否'}`);
    console.log(`Rootless 模式: ${platformHelper.isRootlessEnvironment() ? '是' : '否'}`);
    
    // 测试端口权限
    console.log('\n----- 测试端口权限 -----');
    const testPorts = [80, 443, 8080, 3000];
    for (const port of testPorts) {
        const isPrivileged = platformHelper.isPrivilegedPort(port);
        console.log(`端口 ${port} 是特权端口: ${isPrivileged ? '是' : '否'}`);
        
        if (isPrivileged) {
            const suggestedPort = platformHelper.suggestNonPrivilegedPort(port);
            console.log(`- 建议使用非特权端口: ${suggestedPort}`);
            await platformHelper.showPortPermissionGuide(port);
        }
    }
    
    // 测试路径转换
    console.log('\n----- 测试路径转换 -----');
    const testPaths = [
        __dirname,
        path.join(os.homedir(), 'Documents'),
        '/etc/nginx/conf.d'
    ];
    
    for (const originalPath of testPaths) {
        try {
            const convertedPath = await platformHelper.convertPathForContainer(originalPath);
            console.log(`原路径: ${originalPath}`);
            console.log(`转换后: ${convertedPath}`);
            console.log('---');
        } catch (error) {
            console.error(`转换路径 ${originalPath} 失败:`, error);
        }
    }
    
    // 测试容器选项
    console.log('\n----- 测试容器选项 -----');
    const dockerOptions = platformHelper.getContainerOptions('docker');
    const podmanOptions = platformHelper.getContainerOptions('podman');
    
    console.log('Docker 选项:', Object.keys(dockerOptions).length > 0 ? dockerOptions : '无特殊选项');
    console.log('Podman 选项:', Object.keys(podmanOptions).length > 0 ? podmanOptions : '无特殊选项');
    
    console.log('\n========== 平台支持功能测试完成 ==========');
}

// 执行测试
testPlatformSupport().catch(error => {
    console.error('测试失败:', error);
}); 